package com.kh.pajx.sop.view.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.base.SOPConfig;
import com.kh.pajx.sop.domain.SysDictionary;
import com.kh.pajx.sop.domain.SysMenuAuth;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 系统菜单Struts2控制器
 * @author:	azzcsimp
 * @Createdate:	2014年7月20日 下午8:48:09
 */
@Controller
@Scope("prototype")
public class SysMenuAuthAction extends ModelDrivenBaseAction<SysMenuAuth> {

	private static final long serialVersionUID = -97321164236684887L;
	
	/** 菜单父级编码 */
	private String parentId;
	
	/** 页面转向rel */
	private String relId;
	
	/** 菜单管理 */
	public String main(){
		
		// 获取系统字典数据
		List<SysDictionary> systemDictList = sysDictionaryService.getDicListByTypeCode(SOPConfig.DIC_CODE_SYSTEMNAME);
		
		// 准备树形数据
		ActionContext.getContext().put("menuMap", sysMenuAuthService.getMenuTreeMap(systemDictList));
		
		return "main";
	}
	
	/** 菜单列表 */
	public String list(){
		new QueryHelper(SysMenuAuth.class,"menu")
		.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getSysNameDc())), "menu.sysNameDc=?",StringUtils.trim(model.getSysNameDc()))
		.addCondition(StringUtils.isNotEmpty(StringUtils.trim(parentId)), "menu.parent.menuId=?",StringUtils.trim(parentId))
		.addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getMenuName())), "menu.menuName like ?","%"+StringUtils.trim(model.getMenuName())+"%")
		.addCondition(model.getMenuType()>=0, "menu.menuType=?",model.getMenuType())
		.addOrderProperty("menu.menuOrder", true)
		.preparePageBean(sysMenuAuthService, pageNum, numPerPage);
		return "list";
	}
	
	/** 添加页面 */
	public String addUI(){
		
		// 准备系统名称字典  (目前取单个)
		List<SysDictionary> systemDictList = sysDictionaryService.getDicListByTypeCode(SOPConfig.DIC_CODE_SYSTEMNAME);
		for (SysDictionary dict : systemDictList) {
			if(dict.getDicCode().equals(model.getSysNameDc())){
				ActionContext.getContext().put("sysDict", dict);
			}
		}
		
		// 准备当前系统下菜单列表(用于(上级菜单)回显对照一级菜单(系统))
		List<SysMenuAuth> allMenuBySys = sysMenuAuthService.getMenuTreeListBySys(model.getSysNameDc());
		ActionContext.getContext().put("allMenuBySys", allMenuBySys);
		
		return "saveUI";
	}
	
	/** 添加 */
	public void add(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			if(StringUtils.isNotEmpty(parentId)){
				if(!PropertyValidate.validateUUID(parentId)){
					throw new Exception("上级菜单输入不合法");
				}
				model.setParent(sysMenuAuthService.getById(parentId));  // 上级菜单
			}
			if(StringUtils.isBlank(model.getSysNameDc())&&!PropertyValidate.validateStrByLength(model.getSysNameDc(), 60)){
				throw new Exception("系统编码输入不合法");
				
			}
			if(model.getMenuType()!=0&&model.getMenuType()!=1){
				throw new Exception("菜单类型输入不合法");
			}
			if(StringUtils.isBlank(model.getMenuName())){
				throw new Exception("菜单名称不允许为空");
			}else{
				if(!PropertyValidate.validateStrByLength(model.getMenuName(), 20)){
					throw new Exception("菜单输入不合法");
				}
			}
			if(StringUtils.isNotBlank(model.getMenuUrl())&&!PropertyValidate.validateStrByLength(model.getMenuUrl(), 200)){
				throw new Exception("链接输入不合法");
			}
			if(StringUtils.isNotBlank(model.getMenuDesc())&&!PropertyValidate.validateStrByLength(model.getMenuDesc(), 200)){
				throw new Exception("描述输入不合法");
			}
			if(StringUtils.isNotBlank(model.getMenuTarget())&&!PropertyValidate.validateStrByLength(model.getMenuTarget(), 60)){
				throw new Exception("target输入不合法");
			}
			if(StringUtils.isNotBlank(model.getMenuRel())&&!PropertyValidate.validateStrByLength(model.getMenuRel(), 60)){
				throw new Exception("rel属性不合法");
			}
			model.setSysNameDc(StringUtils.trim(model.getSysNameDc())); // 系统编码
			model.setMenuType(model.getMenuType());  // 菜单类型
			model.setMenuName(StringUtils.trim(model.getMenuName())); // 菜单名称
			model.setMenuUrl(StringUtils.trim(model.getMenuUrl()));  // 菜单URL
			model.setMenuTarget(StringUtils.trim(model.getMenuTarget()));  //target属性
			model.setMenuRel(StringUtils.trim(model.getMenuRel())); // rel属性
			model.setMenuOrder(model.getMenuOrder()); // 排序编码
			model.setMenuDesc(StringUtils.trim(model.getMenuDesc())); // 描述
			model.setMenuStatusFlag(1);
			sysMenuAuthService.save(model);
			dwz.setStatusCode("200");
			dwz.setMessage("保存成功！");
			dwz.setRel("rel_" + model.getSysNameDc());
			dwz.setCallbackType("closeCurrent");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("保存失败！<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/** 修改页面 */
	public String editUI(){
		
		// 准备系统名称字典  (目前取单个)
		List<SysDictionary> systemDictList = sysDictionaryService.getDicListByTypeCode(SOPConfig.DIC_CODE_SYSTEMNAME);
		for (SysDictionary dict : systemDictList) {
			if(dict.getDicCode().equals(model.getSysNameDc())){
				ActionContext.getContext().put("sysDict", dict);
			}
		}
		
		
		// 准备当前系统下菜单列表(用于(上级菜单)回显对照一级菜单(系统))
		List<SysMenuAuth> allMenuBySys = sysMenuAuthService.getMenuTreeListBySys(model.getSysNameDc());
		
		// 准备该菜单对象
		SysMenuAuth menuAuth = sysMenuAuthService.getById(model.getMenuId());
		
		walkRemoveMenu(menuAuth.getChildren(),allMenuBySys);
		allMenuBySys.remove(menuAuth); 	
		
		ActionContext.getContext().put("allMenuBySys", allMenuBySys);
		ActionContext.getContext().getValueStack().push(menuAuth);
		
		return "saveUI";
	}
	
	private void walkRemoveMenu(Collection<SysMenuAuth> children,List<SysMenuAuth> list){
		for (SysMenuAuth obj : children) {
			list.remove(obj);
			walkRemoveMenu(obj.getChildren(),list);
		}
	}
	
	/** 修改 */
	public void edit(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			SysMenuAuth menuAuth = sysMenuAuthService.getById(model.getMenuId());
			if(StringUtils.isBlank(model.getMenuId())||!PropertyValidate.validateUUID(model.getMenuId())){
				throw new Exception("主键被篡改");
			}
			if(StringUtils.isNotEmpty(parentId)){
				if(!PropertyValidate.validateUUID(parentId)){
					throw new Exception("上级菜单输入不合法");
				}
				menuAuth.setParent(sysMenuAuthService.getById(parentId));  // 上级菜单
			} else {
				menuAuth.setParent(null);
			}
			if(StringUtils.isNotBlank(model.getMenuTarget())&&!PropertyValidate.validateStrByLength(model.getMenuTarget(), 60)){
				throw new Exception("target输入不合法");
			}
			if(StringUtils.isNotBlank(model.getMenuRel())&&!PropertyValidate.validateStrByLength(model.getMenuRel(), 60)){
				throw new Exception("rel属性不合法");
			}
			if(model.getMenuType()!=0&&model.getMenuType()!=1){
				throw new Exception("菜单类型输入不合法");
			}
			if(StringUtils.isBlank(model.getMenuName())){
				throw new Exception("菜单名称不允许为空");
			}else{
				if(!PropertyValidate.validateStrByLength(model.getMenuName(), 20)){
					throw new Exception("菜单输入不合法");
				}
			}
			if(StringUtils.isNotBlank(model.getMenuUrl())&&!PropertyValidate.validateStrByLength(model.getMenuUrl(), 200)){
				throw new Exception("链接输入不合法");
			}
			if(StringUtils.isNotBlank(model.getMenuDesc())&&!PropertyValidate.validateStrByLength(model.getMenuDesc(), 200)){
				throw new Exception("描述输入不合法");
			}
			// TODO: 防止前端更改HTML修改系统，目前修改系统还不完善，需要切换Tab 有时间考虑开放
			//menuAuth.setSysNameDc(StringUtils.trim(model.getSysNameDc())); // 系统编码
			menuAuth.setMenuType(model.getMenuType());  // 菜单类型
			menuAuth.setMenuName(StringUtils.trim(model.getMenuName())); // 菜单名称
			menuAuth.setMenuUrl(StringUtils.trim(model.getMenuUrl()));  // 菜单URL
			menuAuth.setMenuTarget(StringUtils.trim(model.getMenuTarget()));  //target属性
			menuAuth.setMenuRel(StringUtils.trim(model.getMenuRel())); // rel属性
			menuAuth.setMenuDesc(StringUtils.trim(model.getMenuDesc())); // 描述
			menuAuth.setMenuOrder(model.getMenuOrder()); // 排序编码
			sysMenuAuthService.update(menuAuth);
			dwz.setStatusCode("200");
			dwz.setMessage("修改成功!");
			dwz.setCallbackType("closeCurrent");
			dwz.setRel("rel_" + menuAuth.getSysNameDc());
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("修改失败！<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/** 删除 */
	public void delete(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			// ==>1.判断是否存在子菜单
			SysMenuAuth menuAuth = sysMenuAuthService.getById(model.getMenuId());
			if(null != menuAuth){
				if(null != menuAuth.getChildren() && menuAuth.getChildren().size() > 0){
					dwz.setMessage("删除失败!<br>错误信息：当前菜单下包含<font color='red'>"+menuAuth.getChildren().size()+"</font>条子级菜单数据！");
					dwz.setStatusCode("300");
					DwzAjaxResult.josnMessage(dwz);
					return;
				}
			}
			
			// TODO ==>2.判断是否存在角色菜单权限
			
			sysMenuAuthService.delete(model.getMenuId());
			dwz.setStatusCode("200");
			dwz.setMessage("删除成功!");
			dwz.setRel("rel_" + model.getSysNameDc());
			dwz.setCallbackType("xxoo");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("删除失败!<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/** 更改状态 */
	public void updateFlag(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			SysMenuAuth menuAuth = sysMenuAuthService.getById(model.getMenuId());
			dwz.setMessage("已成功"+(menuAuth.getMenuStatusFlag()== 1?"停用":"启用")+"菜单<font color='red'>"+menuAuth.getMenuName()+"</font>!");
			menuAuth.setMenuStatusFlag(menuAuth.getMenuStatusFlag()== 1 ? 0 : 1);
			sysMenuAuthService.update(menuAuth);
			dwz.setRel("rel_"+menuAuth.getSysNameDc());
			dwz.setStatusCode("200");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/** 获取一级菜单 
	public String getTopMenuList(){
		List<SysMenuAuth> menuList = sysMenuAuthService.findTopMenuAuthListBySystemCode(model.getSysNameDc());
		ActionContext.getContext().put("menuList", menuList);
		return "menuJson";
	}*/
	
	/** 获取一级菜单 
	public void getTopMenuList2(){
		List<SysMenuAuth> menuList = sysMenuAuthService.findTopMenuListBySys(model.getSysNameDc());
		String jsonStr = "";
		if(menuList!=null && menuList.size()>0){
			jsonStr +="[\"\", \"---请选择---\"]";
			for (int i = 0; i < menuList.size(); i++) {
				jsonStr+=",[\""+menuList.get(i).getMenuId()+"\",\""+menuList.get(i).getMenuName()+"\"]";
			}
		}else{
			jsonStr +="[\"\", \"---请选择---\"]";
		}
		jsonStr = "[" + jsonStr + "]";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");  
		response.setCharacterEncoding("utf-8");
        PrintWriter out = null;  
        try {
			out = response.getWriter();  
			out.println(jsonStr);  
		} catch (IOException e) {
			e.printStackTrace();
		}  
        out.flush();  
		out.close();
	}
	*/
	
	/** 查看 */
	public String show(){
		// 准备系统名称字典
		List<SysDictionary> dicList = sysDictionaryService.getDicListByTypeCode(SOPConfig.DIC_CODE_SYSTEMNAME);
		ActionContext.getContext().put("dicList", dicList);
		
		// 准备菜单信息
		SysMenuAuth menuAuth = sysMenuAuthService.getById(model.getMenuId());
		ActionContext.getContext().getValueStack().push(menuAuth);
		return "show";
	}
	
	
	/** 添加/修改页面 级联菜单 (上级菜单) 目前未启用 */
	public void getMenusBySys(){
		List<SysMenuAuth> menuList = sysMenuAuthService.getMenuTreeListBySys(model.getSysNameDc());
		String jsonStr = "";
		if(menuList!=null && menuList.size()>0){
			jsonStr +="[\"\", \"---请选择---\"]";
			for (int i = 0; i < menuList.size(); i++) {
				jsonStr+=",[\""+menuList.get(i).getMenuId()+"\",\""+menuList.get(i).getMenuName()+"\"]";
			}
		}else{
			jsonStr +="[\"\", \"---请选择---\"]";
		}
		jsonStr = "[" + jsonStr + "]";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");  
		response.setCharacterEncoding("utf-8");
        PrintWriter out = null;  
        try {
			out = response.getWriter();  
			out.println(jsonStr);  
		} catch (IOException e) {
			e.printStackTrace();
		}  
        out.flush();  
	}
	
	/** 获取系统树形结构JSON字符串，用于前端刷新tree */
	public void getMenuTreeData(){
		String jsonStr = sysMenuAuthService.getMenuTreeJson(model.getSysNameDc());
		
		if(StringUtils.isNotEmpty(jsonStr)){
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");  
			response.setCharacterEncoding("utf-8");
	        PrintWriter out = null;  
	        try {
				out = response.getWriter();  
				out.println(jsonStr);  
			} catch (IOException e) {
				e.printStackTrace();
			}  
	        out.flush();  
		}
	}
	

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getRelId() {
		return relId;
	}

	public void setRelId(String relId) {
		this.relId = relId;
	}

	
}
